/*
 * Copyright (c) 2010, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.blogclient;

import java.awt.BorderLayout;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.AbstractAction;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.AbstractTableModel;

import org.panteleyev.blogclient.events.TemplatesChangedEvent;
import org.panteleyev.swing.SwingFactory;
import org.panteleyev.swing.TableUtil;
import org.panteleyev.swing.UIStrings;
import org.panteleyev.swing.WindowManager;
import org.panteleyev.swing.WindowManagerEnumerator;
import org.panteleyev.utilities.events.AppEventListener;

/**
 *
 * @author Petr Panteleyev <petr@panteleyev.org>
 */
class TemplateListFrame extends BloggerFrame {
    private JScrollPane scroller;
    private JTable table;
    private AbstractTableModel tableModel;

    private AbstractAction addAction;
    private AbstractAction editAction;
    private AbstractAction deleteAction;

    private static final String[] headerNames = {
        L10N.TEMPLATE_LIST_FRAME_TABLE_HEADERS_NAME.s(),
        L10N.TEMPLATE_LIST_FRANE_TABLE_HEADERS_DESCR.s(),
        L10N.TEMPLATE_LIST_FRAME_TABLE_HEADERS_HOTKEY.s()
    };

    public TemplateListFrame() {
        setTitle(L10N.TEMPLATE_LIST_FRAME_TITLE.s());

        createActions();
        createMenuBar();
        createContent();

        addAppEventListener(TemplatesChangedEvent.class, new AppEventListener() {
            @Override
            public void eventReceived(EventObject event) {
                tableModel.fireTableDataChanged();
                TableUtil.adjustTableColumnSizes(table, 1, scroller);
            }
        });

        Options.getBounds(this);
    }

    private void createActions() {
        addAction = new AbstractAction(L10N.TEMPLATE_LIST_DIALOG_ADD_ACTION.s(), null) {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onAddTemplate();
            }
        };

        editAction = new AbstractAction(L10N.TEMPLATE_LIST_DIALOG_EDIT_ACTION.s(), null) {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onEditTemplate();
            }
        };

        deleteAction = new AbstractAction(L10N.TEMPLATE_LIST_DIALOG_DELETE_ACTION.s(), null) {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onDeleteTemplate();
            }
        };
        
    }

    private void createMenuBar() {
        createMenuBar(
            createFileMenu(),
            createMenu(UIStrings.MENU_EDIT_NAME.s(), null,
                addAction,
                editAction,
                null,
                deleteAction
            ),
            createToolsMenu(),
            createWindowMenu(),
            createHelpMenu()
        );
    }

    private JPopupMenu createPopupMenu() {
        return SwingFactory.createMenu(null,
            addAction,
            editAction,
            null,
            deleteAction
        ).getPopupMenu();
    }

    private void createContent() {
        tableModel = new AbstractTableModel() {
            @Override
            public int getColumnCount() {
                return headerNames.length;
            }

            @Override
            public String getColumnName(int column) {
                return headerNames[column];
            }

            @Override
            public int getRowCount() {
                return MainClass.getTemplateManager().getTemplateCount();
            }

            @Override
            public Object getValueAt(int row, int column) {
                Template t = MainClass.getTemplateManager().getTemplate(row);
                if (t == null) {
                    return null;
                }

                switch (column) {
                    case 0:
                        return t.getName();
                    case 1:
                        return t.getDescription();
                    case 2:
                        KeyStroke hotKey = t.getHotKey();
                        if (hotKey == null) {
                            return null;
                        } else {
                            String modText = KeyEvent.getKeyModifiersText(hotKey.getModifiers());
                            return modText.replaceAll("\\+", "") + KeyEvent.getKeyText(hotKey.getKeyCode());
                        }

                    default:
                        return null;
                }
            }
        };

        getContentPane().setLayout(new BorderLayout());

        table = new JTable(tableModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        table.setInheritsPopupMenu(true);
        scroller = new JScrollPane(table);

        scroller.setComponentPopupMenu(createPopupMenu());
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() == 2) {
                    onEditTemplate();
                }
            }
        });

        scroller.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent evt) {
                TableUtil.adjustTableColumnSizes(table, 1, scroller);
            }
        });


        getContentPane().add(scroller, BorderLayout.CENTER);
    }

    private void onAddTemplate() {
        new TemplateEditor(new Template()).setVisible(true);
    }

    private void onEditTemplate() {
        int row = table.getSelectedRow();
        if (row != -1) {
            final Template templ = MainClass.getTemplateManager().getTemplate(row);
            if (templ != null) {
                // Find window
                TemplateEditor wnd = (TemplateEditor)WindowManager.find(TemplateEditor.class, new WindowManagerEnumerator<TemplateEditor>() {
                    public boolean frameFound(TemplateEditor frame) {
                        return (frame.getTemplate() == templ);
                    }
                });

                if (wnd != null) {
                    wnd.setVisible(true);
                } else {
                    new TemplateEditor(templ).setVisible(true);
                }
            }
        }
    }

    private void onDeleteTemplate() {
        int row = table.getSelectedRow();
        if (row != -1 && MainClass.showConfirmDialog(this)) {
            final Template templ = MainClass.getTemplateManager().getTemplate(row);
            MainClass.getTemplateManager().deleteTemplate(row);
            tableModel.fireTableDataChanged();
            TableUtil.adjustTableColumnSizes(table, 1, scroller);

            TemplateEditor wnd = WindowManager.find(TemplateEditor.class, new WindowManagerEnumerator<TemplateEditor>() {
                public boolean frameFound(TemplateEditor frame) {
                    return (frame.getTemplate() == templ);
                }
            });

            if (wnd != null) {
                wnd.closeFrame(true);
            }
        }
    }
    
}
